<template>
  <!-- 地图底图 -->
  <div
    id="cesiumContainer"
    :style="{ width: width + 'px', height: height + 'px' }"
  ></div>
</template>

<script>
import * as Cesium from "cesium";
import "cesium/Build/Cesium/Widgets/widgets.css";
export default {
  name: 'CesiumMap',
  data () {
    return {
      viewe: null,
      pointEntities: []
    }
  },
  mounted () {
    this.initMap()
  },
  props: {
    width: {
      type: Number,
      default: () => 1920
    },
    height: {
      type: Number,
      default: () => 1080
    }
  },
  methods: {
    initMap () {
      Cesium.Ion.defaultAccessToken = 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJqdGkiOiIyMjk4ZDlmMy02NjBlLTRiZGItOGMwYi0yNTZlN2VmNDY5NDUiLCJpZCI6NzA3MDMsImlhdCI6MTYzNDU2NjM5NX0.4GwFx_TjzlIuxAzuxIk4X8RfNxmiiUidC0mJSWvKGAk'
      let layer = new Cesium.ArcGisMapServerImageryProvider({
        url: 'https://services.arcgisonline.com/ArcGIS/rest/services/World_Imagery/MapServer',
      })
      this.viewer = new Cesium.Viewer('cesiumContainer', {
        animation: false, // 是否显示动画控件
        shouldAnimate: false,
        homeButton: false, // 是否显示Home按钮
        fullscreenButton: false, // 是否显示全屏按钮
        baseLayerPicker: false, // 是否显示图层选择控件
        geocoder: false, // 是否显示地名查找控件
        timeline: false, // 是否显示时间线控件
        sceneModePicker: false, // 是否显示投影方式控件
        navigationHelpButton: false, // 是否显示帮助信息控件
        infoBox: false, // 是否显示点击要素之后显示的信息
        requestRenderMode: false, // 启用请求渲染模式
        scene3DOnly: true, // 每个几何实例将只能以3D渲染以节省GPU内存
        sceneMode: 3, // 初始场景模式 1 2D模式 2 2D循环模式 3 3D模式  Cesium.SceneMode
        terrainProvider: Cesium.createWorldTerrain(),
        imageryProvider: layer
      })
      //去除版权信息
      this.viewer._cesiumWidget._creditContainer.style.display = "none";
      this.jumpOption({ lon: 118.78, lat: 32.07, height: 20000, duration: 3 })
      this.osmBuilding()
      this.fetchNanjingGeojson(this.viewer)
      this.fetchNJBillboard(this.viewer)
    },
    osmBuilding () {
      let tileset = this.viewer.scene.primitives.add(new Cesium.Cesium3DTileset({
        url: Cesium.IonResource.fromAssetId(96188),
      }))
      tileset.style = new Cesium.Cesium3DTileStyle({
        color: {
          conditions: [
            ["${feature['building']} === 'hospital'", "color('#0000FF')"],
            ["${feature['building']} === 'school'", "color('#00FF00')"],
            [true, "rgba(205,74,152,0.5)"]
          ]
        }
      });
      // console.log(tileset, '3d白模的数据信息')
    },
    jumpOption (obj) {
      this.viewer.camera.flyTo({
        destination: Cesium.Cartesian3.fromDegrees(obj.lon, obj.lat, obj.height),
        duration: obj.duration,
        orientation: {
          heading: Cesium.Math.toRadians(165.0),
          pitch: Cesium.Math.toRadians(-35.0),
          roll: 0.0
        }
      })
    },
    fetchNanjingGeojson: async (viewer) => {
      const nj_dataSource = await Cesium.GeoJsonDataSource.load('/json/nanjing.json', {
        stroke: Cesium.Color.AQUAMARINE,
        fill: Cesium.Color.PINK.withAlpha(0.2),
        strokeWidth: 10,

      })
      viewer.dataSources.add(nj_dataSource)
      // console.log(nj_dataSource, 'oooooooooooo')
      const entities = nj_dataSource.entities.values
      let hashColor = {}
      entities.map((it) => {
        let name = it.name
        let color = hashColor[name]
        if (!color) {
          color = Cesium.Color.fromRandom({
            alpha: 0.3
          })
          hashColor[name] = color
        }
        it.polygon.material = color
        it.polygon.extrudedHeight = 200
      })
    },
    fetchNJBillboard: async (viewer) => {
      const text = ['正常', '报警']
      const { entities } = await Cesium.GeoJsonDataSource.load('/json/nj_points.json')
      entities.values.map((it, i) => {
        // console.log(it, 'llllsssss')
        let t = text[Math.floor(Math.random() * 2)]
        // 坐标转换
        var ellipsoid = viewer.scene.globe.ellipsoid;
        var cartesian3 = new Cesium.Cartesian3(it.position._value.x, it.position._value.y, it.position._value.z);
        var cartographic = ellipsoid.cartesianToCartographic(cartesian3);
        var lng = parseFloat(Cesium.Math.toDegrees(cartographic.longitude).toFixed(6));
        var lat = parseFloat(Cesium.Math.toDegrees(cartographic.latitude).toFixed(6));
        var alt = 200;
        // console.log(lng, lat, alt, 'lkjjjjjjjjjjjjjjj')
        viewer.entities.add({
          name: `water_info${i}`,
          id: it.id,
          position: Cesium.Cartesian3.fromDegrees(lng, lat, alt),
          label: {
            text: t,
            font: '14px 微软雅黑',
            fillColor: t === '正常' ? Cesium.Color.WHITE : Cesium.Color.RED,
            verticalOrigin: Cesium.VerticalOrigin.BOTTOM,
            pixelOffset: new Cesium.Cartesian2(30, -5),
            eyeOffset: new Cesium.Cartesian3(0, 0, -10000)
          },
          point: {
            color: Cesium.Color.RED.withAlpha(0.7),
            pixelSize: 0
          },
          billboard: {
            image: t === '正常' ? '/map/icon-实验室.png' : '/map/icon-在线设备.png',
            width: 16,
            height: 18,
            scale: 1,
            pixelOffset: new Cesium.Cartesian2(0, -12)
          }
        })
      })
    }
  }
}
</script>

<style lang="scss" scoped>
#cesiumContainer {
  width: 100%;
  height: 100%;
  position: relative;
  // top: 2px;
  left: 0px;
  bottom: 0px;
}
</style>